package com.bee.beeAuth.config.securityConfigs;

import com.bee.beeAuth.entity.SysPermission;
import com.bee.beeAuth.entity.SysUser;
import com.bee.beeAuth.service.SysPermissionService;
import com.bee.beeAuth.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 实现UserDetailsService
 * @description:
 * @author: chenguosong
 * @date: 2022-10-18 09:35
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService userService;
    @Resource
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        SysUser user = userService.findUserByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 用户拥有的权限标识
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        List<SysPermission> permissions = permissionService.selectListByUserId(user.getId());
        permissions.forEach(permission -> {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getCode());
            grantedAuthorities.add(grantedAuthority);
        });
        user.setAuthorities(grantedAuthorities);
        return user;
    }
}